import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import importToCDN from 'vite-plugin-cdn-import'
import { visualizer } from 'rollup-plugin-visualizer'

import { createHtmlPlugin } from 'vite-plugin-html'

const getEnvFn = (mode, target) => {
    return loadEnv(mode, process.cwd())[target]
}

function pathResolve(dir: string) {
    return resolve(process.cwd(), '.', dir)
}
// https://vitejs.dev/config/
export default ({ mode }) =>
    defineConfig({
        resolve: {
            alias: [{ find: '@', replacement: pathResolve('src') + '/' }],
        },
        plugins: [
            vue(),
            createHtmlPlugin({
                minify: true,
                /**
                 * 在这里写entry后，你将不需要在`index.html`内添加 script 标签，原有标签需要删除
                 * @default src/main.ts
                 */
                // entry: 'src/main.ts',
                /**
                 * 需要注入 index.html ejs 模版的数据
                 */
                inject: {
                    data: {
                        title: getEnvFn(mode, 'VITE_APP_TITLE'),
                        // injectScript: `<script src="./inject.js"></script>`,
                    },
                    // tags: [
                    //     {
                    //         injectTo: 'body-prepend',
                    //         tag: 'div',
                    //         attrs: {
                    //             id: 'tag',
                    //         },
                    //     },
                    // ],
                },
            }),
            visualizer(),
            importToCDN({
                modules: [
                    {
                        name: 'vue',
                        var: 'Vue',
                        path: `https://unpkg.com/vue@3.2.33/dist/vue.global.prod.js`,
                    },
                    {
                        name: 'vue-router',
                        var: 'VueRouter',
                        path: `https://unpkg.com/vue-router@4.0.14/dist/vue-router.global.prod.js`,
                    },
                    {
                        name: 'axios',
                        var: 'axios',
                        path: `https://unpkg.com/axios@0.25.0/dist/axios.min.js`,
                    },
                ],
            }),
        ],
    })
